# -=- encoding: UTF-8

from django.db import models
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
from adl.base.models import Usercreated
from adl.guild.models import Rank

class ForumCategory(Usercreated):
    "Forenkategorie."
    """
        Forenkategorien dienen zum Organisieren von einzelnen Foren.
        Benutzerberechtigungen werden über die Kategorien geregelt.
        
        >>> from adl.board.models import ForumCategory
        >>> fcat = ForumCategory.objects.all()[0]
        >>> from adl.guild.models import Character
        >>> general = Character.current.filter(name="Silvana")[0]
        >>> reservist = Character.current.filter(name="Arnheimer")[0]
        >>> fcat._check_permission(reservist, 'min_rank_read')
        True
        >>> fcat._check_permission(reservist, 'min_rank_write')
        False
        >>> fcat._check_permission(reservist, 'min_rank_moderate')
        False
        >>>
        >>> fcat.check_read_permission(reservist)
        True
        >>> fcat.check_write_permission(reservist)
        False
        >>> fcat.check_mod_permission(reservist)
        False
        
    """
    name              = models.CharField(max_length = 255)
    description       = models.TextField()
    min_rank_read     = models.ManyToManyField(to = Rank, blank = True, verbose_name = u"Mindestrang Lesen", help_text = u"Mindestrang zur Ansicht der Kategorie.", related_name = "read_permissions")
    min_rank_write    = models.ManyToManyField(to = Rank, blank = True, verbose_name = u"Mindestrang Schreiben", help_text = u"Mindestrang zum Anlegen in der Kategorie.", related_name = "write_permissions")
    min_rank_moderate = models.ManyToManyField(to = Rank, blank = True, verbose_name = u"Mindestrang Moderieren", help_text = u"Mindestrang zum Moderieren in der Kategorie.", related_name = "mod_permissions")
    
    class Meta:
        verbose_name = u"Forumkategorie"
        verbose_name_plural = u"Forumkategorien"      

    def __unicode__(self):
        return u"%s" % self.name
    
    def _check_permission(self, user, fieldname):
        rank_set = getattr(self, fieldname).all()       # ManyRelatedManager
        if len(rank_set) == 0: return True              # wenn keine angegeben, dann alle
        for rank in rank_set:
            if user.rank >= rank: return True
        return False    
    
    def check_read_permission(self, user):
        return self._check_permission(user, 'min_rank_read')
    
    def check_write_permission(self, user):
        return self._check_permission(user, 'min_rank_write')
    
    def check_mod_permission(self, user):
        return self._check_permission(user, 'min_rank_moderate')   
    
class Forum(Usercreated):
    name = models.CharField(max_length = 255)
    description = models.TextField()
    category = models.ForeignKey(to = ForumCategory, null = False)
    
    def category_link(self):        
        return u'<a href="/admin/board/forumcategory/%s">%s</a>' % (self.category.id, self.category.name)
    category_link.allow_tags = True
    
    class Meta:
        order_with_respect_to = 'category'
        verbose_name = "Forum"
        verbose_name_plural = "Foren"
        
    def __unicode__(self):
        return u"%s" % self.name
    
    def thread_with_latest_post(self):
        return Post.objects.filter(thread__forum=self).latest()
    
    def count_threads(self):
        return self.thread_set.count()
    
    def count_posts(self):
        threads = self.thread_set.all()
        sum = 0
        for thread in threads:
            sum = sum + thread.post_set.count()
        return sum

class Thread(Usercreated):
    is_sticky = models.BooleanField(default = False)
    forum = models.ForeignKey(to = Forum, null = False)
    title = models.CharField(max_length = 255)
    accesscount = models.IntegerField(null = True)

    def category_link(self):        
        return u'<a href="/admin/board/forumcategory/%s">%s</a>' % (self.forum.category.id, self.forum.category.name)
    category_link.allow_tags = True
    
    def forum_link(self):        
        return u'<a href="/admin/board/forum/%s">%s</a>' % (self.forum.id, self.forum.name)
    forum_link.allow_tags = True    

    class Meta:
        order_with_respect_to = 'forum'
        verbose_name = "Thread"
        verbose_name_plural = "Threads"
        
    def __unicode__(self):
        return self.title
    
    def latest_post(self):
        return self.post_set.latest()
    
    def first_post(self):
        return self.post_set.all().order_by('created')[0]

class Post(Usercreated):
    thread = models.ForeignKey(to = Thread, null = False)
    text = models.TextField(verbose_name="Text des Beitrags", name="Text")
    
    read_by = models.ManyToManyField(User, through='ReadBy', related_name='read_set', null = True)

    class Meta:
        get_latest_by = "created"
        ordering = ["-created", "-modified"]
        order_with_respect_to = 'thread'
        verbose_name = "Eintrag"
        verbose_name_plural = "EintrÃ¤ge"
        
    def __unicode__(self):
        return self.thread.title + " (Antwort vom %s in %s)" % (self.created, self.thread.forum)
    
class ReadBy(models.Model):
    post = models.ForeignKey(Post)
    user = models.ForeignKey(User)
    date_read = models.DateTimeField(auto_now_add = True)
